<?php

namespace api\wechat;

//预订菜单类
use utils\base64_to_file;
use utils\oss;

class pre
{
    //获取预订菜单拥有的分类
    public function getCategory($request)
    {

        //登录检测，未注册的自动注册为默认用户
        if (empty($request['openid'])) {
            return out_error('非法访问！');
        }
//
//        $this->checkLogin($request);

        $con = con();
        if (isset($request['pre_time'])) {
            $pre_time = strtotime($request['pre_time']);
            $date = date('Y-m-d', $pre_time);
            $time = $pre_time - strtotime($date);
        } else {
            $date = date('Y-m-d');
            $time = time() - strtotime($date);
        }
        $category = mysqli_query($con, "select * from setting where id in (1,2,3) and value_1<=$time and value_2>$time");
        $category = mysqli_fetch_all($category, true);
        if (count($category) == 0) {
            mysqli_close($con);
            return out_error('未在用餐时间！');
        }
        $type = (int)$category[0]['id'];
        $start_time = strtotime($date) + $category[0]['value_1'];
        $end_time = strtotime($date) + $category[0]['value_2'];
        $menu_id = mysqli_query($con, "select * from pre where is_delete=1 and status=1 and date like '%$date%'");
        $menu_id = mysqli_fetch_all($menu_id, true);
        if (count($menu_id) == 0) {
            mysqli_close($con);
            return out_error('请后台设置菜单！');
        }
        switch ($type) {
            case 1:
                $vip_price = $menu_id[0]['price_vip_1'];
                $price = $menu_id[0]['price_1'];
                break;
            case 2:
                $vip_price = $menu_id[0]['price_vip_2'];
                $price = $menu_id[0]['price_2'];
                break;
            case 3:
                $vip_price = $menu_id[0]['price_vip_3'];
                $price = $menu_id[0]['price_3'];
                break;
            default:
                mysqli_close($con);
                return out_error('非法访问！');
                break;
        }
        $menu_id = array_column($menu_id, 'id');
        $menu_id = implode(',', $menu_id);
       // $goods = mysqli_query($con, "select * from pre_goods_config where is_delete=1 and status=1 and type=$type and menu_id in ($menu_id)");
        $goods = mysqli_query($con, "select * from pre_goods_config where is_delete=1 and status=1  and menu_id in ($menu_id)");
        $goods = mysqli_fetch_all($goods, true);

        $goods_ids = implode(',', array_column($goods, 'goods_id'));
        if (empty($goods_ids)) {
            mysqli_close($con);
            return out_error('该菜单无商品！');
        }
        $category_ids = mysqli_query($con, "select * from goods_category_config where is_delete=1 and status=1 and goods_id in ($goods_ids)");
        $category_ids = mysqli_fetch_all($category_ids, true);
        if (count($category_ids) == 0) {
            mysqli_close($con);
            return out_error('该时段此菜单无商品！');
        }
        $category_ids = implode(',', array_column($category_ids, 'category_id'));

        $data = mysqli_query($con, "select * from category where is_delete=1 and status=1 and id in ($category_ids) order by `sort` ASC ");
        $data = mysqli_fetch_all($data, true);

        $openid = $request['openid'];
        $user = mysqli_query($con, "select * from user where openid='$openid'");
        $user = mysqli_fetch_all($user, true);
        if (count($user) === 0) {//检测到未注册用户，则自动注册默认用户
            //强制登录
            mysqli_close($con);
            return out_not_login();
//            mysqli_query($con, "insert into user(openid,nickname,avatar,create_time) values('$openid','普通用户','https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png',$time)");
//            $user_id=(int)mysqli_insert_id($con);
//            $is_vip=false;
        }else{
            $user_id = (int)$user[0]['id'];
            $res=mysqli_query($con,"select * from user_power_config where status=1 and is_delete=1 and user_id=$user_id and type in (5,7) and check_status=1");
            $res=mysqli_num_rows($res);
            if($res===0){
                $is_vip =false;
            }else{
                $is_vip =true;
            }
        }


        $order = mysqli_query($con, "select * from `order` where user_id=$user_id and time_type=$type and status in (0,1) and is_delete=1 and (create_time between $start_time and $end_time ) ");
        $order = mysqli_num_rows($order);
        mysqli_close($con);


        array_unshift($data,[

            "id"=> "0",
            "name"=> "全部",
            "type"=> "0",
            "sort"=> "1",
            "create_time"=> "1723558746",
            "update_time"=> "1729487808",
            "delete_time"=> null,
            "remark"=> "",
            "is_delete"=> "1",
            "status"=> "1"

        ]);

        return out_right([
            'category' => $data,
            'type' => $type,
            'price_vip' => sprintf('%.2f', $vip_price / 100),
            'price' => sprintf('%.2f', $price / 100),
            'is_vip' => $is_vip,
            'order' => $order,
            'user_id'=>$user_id
        ]);
    }


    //根据分类和时段类型检索对应商品
    public function getAllByCategory($request)
    {
        $category_id = (int)$request['category_id'];
        $openid = $request['openid'];
        $con = con();


        //过滤合法菜单的商品id出来
        if (isset($request['pre_time'])) {
            $pre_time = strtotime($request['pre_time']);
            $date = date('Y-m-d', $pre_time);
            $time = $pre_time - strtotime($date);
        } else {
            $date = date('Y-m-d');
            $time = time() - strtotime($date);
        }
        $category = mysqli_query($con, "select * from setting where id =10 and value_1<=$time and value_2>$time");
        $category = mysqli_fetch_all($category, true);
        if (count($category) == 0) {
            mysqli_close($con);
            return out_error('不在营业时间段');
        }
        $time_type = (int)$category[0]['id'];
        $type = (int)$category[0]['id'];
        $menu_id = mysqli_query($con, "select * from pre where is_delete=1 and status=1 and date like '%$date%'");
        $menu_id = mysqli_fetch_all($menu_id, true);
        if (count($menu_id) == 0) {
            mysqli_close($con);
            return out_error('此时间段无菜单！请后台设置！');
        }
        $menu_name = $menu_id[0]['name'];
        $menu_id = (int)$menu_id[0]['id'];
        $goods = mysqli_query($con, "select * from pre_goods_config where is_delete=1 and status=1 and type in (1) and menu_id = $menu_id");
        $goods = mysqli_fetch_all($goods, true);

        $goods_ids = array_column($goods, 'goods_id');

        //检索用户合法性
        $res = mysqli_query($con, "select * from user where openid='$openid'");
        $res = mysqli_fetch_all($res, true);
        if (count($res) === 0) {
            mysqli_close($con);
            return out_error('非法访问！请先登录！');
        }
        $user_id = (int)$res[0]['id'];
        $is_vip = (int)$res[0]['is_vip'];

        if($category_id===0){
            $a='';
        }else{
            $a=" m.category_id=$category_id and ";
        }


        $data = mysqli_query($con, "select xx.*,0 as num,IFNULL(yy.specs,'[]') as specs from (SELECT n.* FROM `goods_category_config` m join goods n on (m.goods_id=n.id) where $a m.is_delete=1 and m.status=1 and n.is_delete=1 and n.`status`=1) xx LEFT JOIN (select x.goods_id,JSON_ARRAYAGG(JSON_OBJECT('id',y.id,'name',y.name,'active',0,'item',y.item)) as specs from goods_specs_config x  join (select a.*,JSON_ARRAYAGG(b.`value`) as item from specs a  LEFT JOIN specs_value_config b on (a.id=b.specs_id) where a.is_delete=1 and a.`status`=1 and b.is_delete=1 and a.`status`=1 GROUP BY a.id) y on (x.specs_id=y.id) where x.is_delete=1 and x.`status`=1 GROUP BY x.goods_id) yy on (xx.id=yy.goods_id)");
        $data = mysqli_fetch_all($data, true);
        $start = strtotime(date('Y-m-d'));
        $record = mysqli_query($con, "select * from pre_day_record where menu_id=$menu_id and type=$time_type and create_time>=$start");
        $record = mysqli_fetch_all($record, true);

        if (count($record) === 0) {
            $record_goods_id = [];
            $comment = [];
        } else {
            $record_goods_id = array_column($record, 'goods_id');
            $record_ids = array_column($record, 'id');
            $record_ids = implode(',', $record_ids);
            $comment = mysqli_query($con, "select a.*,b.goods_id,b.id as record_id,b.goods_name,b.goods_url from pre_day_record_coment a LEFT JOIN pre_day_record b on (a.menu_day_record_id=b.id) where a.status=1 and a.is_delete=1 and a.menu_day_record_id in ($record_ids) and a.user_id=$user_id");
            $comment = mysqli_fetch_all($comment, true);
        }
        switch ($time_type) {
            case 1://早餐
                $time_type_text = '早餐';
                break;
            case 2://早餐
                $time_type_text = '午餐';
                break;
            case 3://早餐
                $time_type_text = '晚餐';
                break;
            default:
                $time_type_text = '';
                break;
        }

        $res = [];
        for ($i = 0; $i < count($data); $i++) {
            if (empty($data[$i]['img_url'])) {
                $data[$i]['img_url'] = [];
            } else {
                $data[$i]['img_url'] = explode(',', $data[$i]['img_url']);
            }
            if ($is_vip === 1) {
                $data[$i]['price'] = $data[$i]['vip_price'];
            } else {
                $data[$i]['vip_price'] = $data[$i]['price'];
            }

            if (in_array($data[$i]['id'], $goods_ids)) {
                $res[] = $data[$i];
            }
        }
        $data=$res;


        $add = [];
        $time = time();
        $temp = [
            "id" => 0,
            "menu_id" => $menu_id,
            "menu_name" => $menu_name,
            "type" => $time_type,
            "goods_id" => 0,
            "goods_name" => "",
            "goods_url" => [],
            "remark" => null,
            "has_coment" => false,
            "has_coment_text" => "未评价",
            "coment" => null,
            "date" => $date,
            "type_text" => $time_type_text
        ];
        for($i=0;$i<count($data);$i++){
            $a=$temp;
            $data[$i]['status_comment'] = false;
            $goods_id = (int)$data[$i]['id'];
            $goods_name = $data[$i]['name'];
            $goods_url = $data[$i]['img_url'];
            $a['goods_id']=$goods_id;
            $a['goods_name']=$goods_name;
            $a['goods_url']=$goods_url;
            if (!in_array($data[$i]['id'], $record_goods_id)) {//判断是否存在评价记录，不存在则插入记录
                $b=implode(',',$goods_url);
                mysqli_query($con, "insert into pre_day_record(menu_id,menu_name,type,goods_id,goods_name,goods_url,create_time,update_time) values($menu_id,'$menu_name',$time_type,$goods_id,'$goods_name','$b',$time,$time)");
                $id=mysqli_insert_id($con);
                $a['id']=$id;
            } else {//存在记录
                for($o=0;$o<count($record);$o++){//遍历记录数据
                    if($data[$i]['id']==$record[$o]['goods_id']){
                        $a['id']=$record[$o]['id'];
                    }
                }
                for ($o = 0; $o < count($comment); $o++) {//遍历评论数据
                    if ($data[$i]['id'] === $comment[$o]['goods_id']) {
                        $a['has_coment']=true;
                        $a['has_coment_text']='已评价';
                        if(empty($comment[$o]['img_url'])){
                            $comment[$o]['img_url']=[];
                        }else{
                            $comment[$o]['img_url']=explode(',',$comment[$o]['img_url']);
                        }
                        $a['coment']=$comment[$o];
                        $data[$i]['status_comment'] = true;
                    }
                }
            }
            $data[$i]['comment_info'] = $a;
        }
        mysqli_close($con);
        return out_right($data);
    }

    //评价预订菜单
    public function up($data){
        $con=con();
        $openid=$data['openid'];
        $content=$data['content'];
        $img=$data['img'];
        $type=(int)$data['type'];
        $menu_day_record_id = (int)$data['menu_day_record_id'];
        $date=date('Y-m-d');
        $url=[];

        $user_id=mysqli_query($con,"select * from user where openid='$openid' ");
        $user_id=mysqli_fetch_all($user_id,true);
        if(count($user_id)==0){
            mysqli_close($con);
            return out_error('查无此人！');
        }
        $user_id=(int)$user_id[0]['id'];

        for($i=0;$i<count($img);$i++){
            $file=base64_to_file::get("",$img[$i]["file_name"],$img[$i]["file"]);
            $res=oss::upload("pre/$date/".$file["name"],$file["path"]);
            $url[]=$res["info"]["url"];
        }
        if(empty($url)){
            $url='';
        }else{
            $url=implode(',',$url);
        }
        $time=time();
        $res=mysqli_query($con,"insert into pre_day_record_coment(menu_day_record_id,user_id,type,img_url,content,create_time,update_time) values($menu_day_record_id,$user_id,$type,'$url','$content',$time,$time)");
        mysqli_close($con);
        if($res){
            return out_right();
        }else{
            return out_error('评价失败！');
        }
    }

}